package _11alliyun;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;

import java.io.*;

/**
 * @ClassName OSSsimpleUplade
 * @Description: 阿里云oss文件上传测试
 * @Author Administrator
 * @Date 2020/4/8
 **/
public class OSSsimpleUplade {

    //oss工作空间的网址
    private static String endpoint = "oss-cn-chengdu.aliyuncs.com";

    //阿里云账号key和Secret，这个账号必须拥有oss的读写权限
    private static String accessKeyId = "LTAI4Feeeeeeee";
    private static String accessKeySecret = "jbcnxxxxxxxxx";

    //上传到哪个bucket
    private static String bucketName = "yuchenoss";

    //上传到哪个文件夹路径下，如果不存在会自动创建
    private static String mkdir = "jd/images";

    public static void main(String[] args) throws IOException {
        /*
         * 构建上传对象
         */
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {

            /**
             * Note that there are two ways of uploading an object to your bucket, the one
             * by specifying an input _4stream as content source, the other by specifying a file.
             */

            /*
             * 准备文件
             */
            File file=new File("D:/index.jpg");
            FileInputStream in = new FileInputStream(file);


            //创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();

            //上传的文件的长度
            metadata.setContentLength(in.available());

            //指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("max-age=3600");
            //指定该Object下设置Header
            //metadata.setHeader("Pragma", "no-cache");
            metadata.setObjectAcl(CannedAccessControlList.PublicRead);

            //指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");

            //文件的MIME类型，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成
            //必须设置才能在网页中在线查看，否则只提供下载
            String fileName = file.getName();
            metadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));

            //指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
            metadata.setContentDisposition(fileName);



            /*
             * 开始上传
             */
            PutObjectResult result = client.putObject(bucketName, mkdir+"/"+System.currentTimeMillis()+fileName, in, metadata);
            System.out.println(result.getETag());
            System.out.println(result.getRequestId());
//            ResponseMessage response = result.getResponse();
//            System.out.println(response.getErrorResponseAsString());
//            System.out.println(response.getUri());
//            System.out.println(response.getStatusCode());


        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorMessage());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
        } finally {
            /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */
            client.shutdown();
        }
    }


    /**
     * 判断文件后缀名的类型，并返回一个对应的浏览器类型
     * @param FilenameExtension
     * @return
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }

}
